package com.hemaapp.yjnh.activity;

import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;

import de.greenrobot.event.EventBus;
import xtom.frame.XtomActivityManager;
import xtom.frame.image.load.XtomImageTask.Size;
import xtom.frame.util.XtomBaseUtil;
import xtom.frame.util.XtomFileUtil;
import xtom.frame.util.XtomSharedPreferencesUtil;
import xtom.frame.util.XtomToastUtil;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.android.uu.view.ActionSheetDialog;
import com.android.uu.view.ActionSheetDialog.OnSheetItemClickListener;
import com.android.uu.view.ActionSheetDialog.SheetItemColor;
import com.hemaapp.BaseConfig;
import com.hemaapp.hm_FrameWork.HemaImageWay;
import com.hemaapp.hm_FrameWork.HemaNetTask;
import com.hemaapp.hm_FrameWork.result.HemaArrayResult;
import com.hemaapp.hm_FrameWork.result.HemaBaseResult;
import com.hemaapp.yjnh.BaseActivity;
import com.hemaapp.yjnh.BaseHttpInformation;
import com.hemaapp.yjnh.R;
import com.hemaapp.yjnh.bean.EventBusConfig;
import com.hemaapp.yjnh.bean.EventBusMsg;
import com.hemaapp.yjnh.bean.User;
import com.hemaapp.yjnh.nettask.ImageAvatarTask;
import com.hemaapp.yjnh.utils.ImageUtils;
import com.hemaapp.yjnh.view.YjnhImageWay;

public class Register2Activity extends BaseActivity implements
		OnClickListener {

	private static final int REQUEST_NICKNAME = 0x101;
	
	private ImageButton left;
	private TextView title;
	private Button right;
	
	private LinearLayout ll_nickname;
	private LinearLayout ll_sex;
	private TextView nickname;
	private TextView sex;
	private ImageView avatar;

	private String username;
	private String password;
	private String invite_phone;
	private String tempToken;

	private YjnhImageWay imageWay;
	private String tempPath;
	private String nickname_p = "";
	private String sex_p = "";
	private int type = 0;//显示类型：1注册时完善个人信息，2注册完成后修改个人信息
	private String imagePathCamera;
	private String token = "";
//	private String lat = "";//纬度
//    private String lng = "";//经度
	private String distirct = "";//地区

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		setContentView(R.layout.activity_register2);
		super.onCreate(savedInstanceState);
//		lat = XtomSharedPreferencesUtil.get(mContext, "lat");
//		lng = XtomSharedPreferencesUtil.get(mContext, "lng");
		distirct = XtomSharedPreferencesUtil.get(mContext, "city");
		if (savedInstanceState == null) {
			imageWay = new YjnhImageWay(mContext, 1, 2);
		} else {
			imagePathCamera = savedInstanceState.getString("imagePathCamera");
			imageWay = new YjnhImageWay(mContext, 1, 2);
		}
	}

	@Override
	protected void onSaveInstanceState(Bundle outState) {
		if (imageWay != null)
			outState.putString("imagePathCamera", imageWay.getCameraImage());
		super.onSaveInstanceState(outState);
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		if (RESULT_OK != resultCode) {
			return;
		}
		switch (requestCode) {
		case 1:// 相册选择图片
			album(data);
			break;
		case 2:// 拍照
			camera();
			break;
		case 3:// 裁剪
			imageWorker.loadImage(new ImageAvatarTask(avatar, tempPath, mContext,
					new Size(180, 180)));
			break;
		case REQUEST_NICKNAME:
			nickname_p = data.getStringExtra("content");
			nickname.setText(nickname_p);
			break;
		default:
			break;
		}
		super.onActivityResult(requestCode, resultCode, data);
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.title_left_btn:
			finish();
			break;
		case R.id.avatar:
			showPic();
			break;
		case R.id.title_right_btn:
//			if (isNull(tempPath)) {//头像不是必选项
//				showTextDialog("请选择头像");
//				break;
//			}
			if (isNull(nickname_p)) {
				XtomToastUtil.showShortToast(mContext, "请输入昵称");
				break;
			}
			if (isNull(sex_p)) {
				XtomToastUtil.showShortToast(mContext, "请选择性别");
				break;
			}
			String area = XtomSharedPreferencesUtil.get(mContext, "address");
			if (type == 1) {//1注册时完善个人信息，
				getNetWorker().clientAdd(tempToken, username, password, invite_phone, distirct);
			}else if (type == 2) {//2注册完成后查看个人信息
				getNetWorker().clientSave(getApplicationContext().getUser().getToken(), 
						nickname_p, sex_p, "无", "无");
			}
			break;
		case R.id.ll_nickname:
			Intent itNick = new Intent(mContext, DataModifyActivity.class);
			itNick.putExtra("hint_name", "昵称");
			itNick.putExtra("name", nickname_p);
			itNick.putExtra("type", 1);
			startActivityForResult(itNick, REQUEST_NICKNAME);
			break;
		case R.id.ll_sex:
			showSex();
			break;
		default:
			break;
		}
	}
	
	/**
	 * 显示图片选择对话
	 */
	public void showPic() {
	    new ActionSheetDialog(mContext)
        .builder()
        .setCancelable(true)
        .setCanceledOnTouchOutside(true)
        .addSheetItem("相机", SheetItemColor.Black,
                new OnSheetItemClickListener() {
                    @Override
                    public void onClick(int which) {
                        imageWay.camera();
                    }
                })
        .addSheetItem("从相册打开", SheetItemColor.Black,
                new OnSheetItemClickListener() {
                    @Override
                    public void onClick(int which) {
                        imageWay.album();
                    }
                })
        .show();
	}
	
	/**
	 * 显示性别选择对话
	 */
	public void showSex() {
	    new ActionSheetDialog(mContext)
        .builder()
        .setCancelable(true)
        .setCanceledOnTouchOutside(true)
        .addSheetItem("男", SheetItemColor.Black,
                new OnSheetItemClickListener() {
                    @Override
                    public void onClick(int which) {
                    	sex_p = "男";
    					sex.setText(sex_p);
                    }
                })
        .addSheetItem("女", SheetItemColor.Black,
                new OnSheetItemClickListener() {
                    @Override
                    public void onClick(int which) {
                    	sex_p = "女";
    					sex.setText(sex_p);
                    }
                })
        .show();
	}
	
	@Override
	protected void callBeforeDataBack(HemaNetTask netTask) {
		// TODO Auto-generated method stub
		BaseHttpInformation info = (BaseHttpInformation) netTask
				.getHttpInformation();
		switch (info) {
		case CLIENT_ADD:
			showProgressDialog("正在注册");
			break;
		case CLIENT_SAVE:
			showProgressDialog("正在保存");
			break;
		case FILE_UPLOAD:
			showProgressDialog("正在上传头像");
			break;
		default:
			break;
		}
	}

	@Override
	protected void callAfterDataBack(HemaNetTask netTask) {
		// TODO Auto-generated method stub
		BaseHttpInformation info = (BaseHttpInformation) netTask
				.getHttpInformation();
		switch (info) {
		case CLIENT_ADD:
		case CLIENT_SAVE:
		case FILE_UPLOAD:
			cancelProgressDialog();
			break;
		default:
			break;
		}
	}

	@Override
	protected void callBackForServerSuccess(HemaNetTask netTask,
			HemaBaseResult baseResult) {
		BaseHttpInformation information = (BaseHttpInformation) netTask
				.getHttpInformation();
		switch (information) {
		case CLIENT_ADD:
			XtomToastUtil.showShortToast(mContext, "注册成功");
			HemaArrayResult<String> tResult=(HemaArrayResult<String>) baseResult;
			token = tResult.getObjects().get(0);
			getNetWorker().clientSave(token, nickname_p, sex_p, "无", "无");
			break;
		case CLIENT_LOGIN:
			HemaArrayResult<User> uResult = (HemaArrayResult<User>) baseResult;
			User user = uResult.getObjects().get(0);
			getApplicationContext().setUser(user);
			if (type == 1) {
				String username = netTask.getParams().get("username");
				String password = netTask.getParams().get("password");
				XtomSharedPreferencesUtil.save(mContext, "username", username);
				XtomSharedPreferencesUtil.save(mContext, "password", password);
                XtomActivityManager.finishAll();
                Intent it = new Intent(mContext, MainActivity.class);
                startActivity(it);
			}else {
                EventBusMsg msg = new EventBusMsg();
                msg.setType(EventBusConfig.USER);
                msg.setUser(user);
                EventBus.getDefault().post(msg);
                finish();
			}
			break;
		case CLIENT_SAVE:
			XtomToastUtil.showShortToast(mContext, "保存成功");
			if(!isNull(tempPath) && !tempPath.startsWith("http")){
				getNetWorker().fileUpload(token, "1", "0",
						"0", "0", "无", tempPath);
			}else if (1 == type) {
				getNetWorker().clientLogin(username, password);
			}else {
				getNetWorker().clientLogin();
			}
			break;
		case FILE_UPLOAD:
			showTextDialog("头像上传成功");
			//文件上传成功后，重新登陆刷新本地数据
			if (type == 1) {
				getNetWorker().clientLogin(username, password);
			}else {
				getNetWorker().clientLogin();
//				setResult(RESULT_OK);
//				finish();
			}
			break;
		default:
			break;
		}
	}

	private void toLogin() {
		XtomActivityManager.finishAll();
		Intent it = new Intent(mContext, LoginActivity.class);
		startActivity(it);
	}

	@Override
	protected void callBackForServerFailed(HemaNetTask netTask,
			HemaBaseResult baseResult) {
		BaseHttpInformation information = (BaseHttpInformation) netTask
				.getHttpInformation();
		switch (information) {
		case INIT:
			// getInitFailed();
			break;
		case CLIENT_LOGIN:
			toLogin();
			break;
		case CLIENT_ADD:
			XtomToastUtil.showShortToast(mContext, "注册失败,"+baseResult.getMsg());
			break;
		case CLIENT_SAVE:
			XtomToastUtil.showShortToast(mContext, "保存失败,"+baseResult.getMsg());
			break;
		case FILE_UPLOAD:
			XtomToastUtil.showShortToast(mContext, "头像上传失败,"+baseResult.getMsg());
			if (type == 1) {
				getNetWorker().clientLogin(username, password);
			}else 
				getNetWorker().clientLogin();
			break;
		default:
			break;
		}
	}

	@Override
	protected void callBackForGetDataFailed(HemaNetTask netTask, int failedType) {
		BaseHttpInformation information = (BaseHttpInformation) netTask
				.getHttpInformation();
		switch (information) {
		case INIT:
			// getInitFailed();
			break;
		case CLIENT_LOGIN:
			toLogin();
			break;
		case CLIENT_ADD:
			XtomToastUtil.showShortToast(mContext, "注册失败");
			break;
		case CLIENT_SAVE:
			XtomToastUtil.showShortToast(mContext, "保存失败");
			break;
		case FILE_UPLOAD:
			XtomToastUtil.showShortToast(mContext, "头像上传失败");
			if (type == 1) {
				getNetWorker().clientLogin(username, password);
			}else 
				getNetWorker().clientLogin();
			break;
		default:
			break;
		}
	}

	@Override
	protected void findView() {
		left = (ImageButton) findViewById(R.id.title_left_btn);
		title = (TextView) findViewById(R.id.title_text);
		right = (Button) findViewById(R.id.title_right_btn);

		ll_nickname = (LinearLayout) findViewById(R.id.ll_nickname);
		ll_sex = (LinearLayout) findViewById(R.id.ll_sex);
		nickname = (TextView) findViewById(R.id.nickname);
		sex = (TextView) findViewById(R.id.sex);
		avatar = (ImageView) findViewById(R.id.avatar);
	}

	@Override
	protected void getExras() {
		type = getIntent().getIntExtra("type", 0);
		if (type == 1) {
			username = getIntent().getStringExtra("username");
			password = getIntent().getStringExtra("password");
			tempToken = getIntent().getStringExtra("tempToken");
			invite_phone = getIntent().getStringExtra("invitation");
		}else if (type == 2) {
			User user = getApplicationContext().getUser();
			token = user.getToken();
			if (null != user) {
				nickname_p = user.getNickname();
				sex_p = user.getSex();
			}
		}
	}
	
	private void setData() {
		nickname.setText(nickname_p);
		sex.setText(sex_p);
        tempPath = getApplicationContext().getUser().getAvatar();
        ImageUtils.loadAvatar(mContext, tempPath, avatar);
	}

	@Override
	protected void setListener() {
		left.setOnClickListener(this);
		title.setText("完善资料");
		right.setVisibility(View.VISIBLE);
//		if (type == 1) {
//			right.setText("注册");
//		}else {
//			right.setText("保存");
//			setData();
//		}
		right.setText("保存");
		if (type == 2) {
			setData();
		}
		avatar.setOnClickListener(this);
		ll_nickname.setOnClickListener(this);
		ll_sex.setOnClickListener(this);
		right.setOnClickListener(this);
	}

	private void album(Intent data) {
		if (data == null)
			return;
//		ArrayList<String> imgList = data.getStringArrayListExtra("images");
//		if (imgList == null)
//			return;
//		editImage(imgList.get(0), 3);
		Uri selectedImageUri = data.getData();
		startPhotoZoom(selectedImageUri, 3);
	}

	private void editImage(String path, int requestCode) {
		File file = new File(path);
		startPhotoZoom(Uri.fromFile(file), requestCode);
	}

	private void startPhotoZoom(Uri uri, int requestCode) {
		Intent intent = new Intent("com.android.camera.action.CROP");
		intent.putExtra(MediaStore.EXTRA_OUTPUT, getTempUri());
		intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
		intent.putExtra("noFaceDetection", false);
		intent.putExtra("scale", true);
		intent.putExtra("scaleUpIfNeeded", true);
		intent.setDataAndType(uri, "image/*");
		// 下面这个crop=true是设置在开启的Intent中设置显示的VIEW可裁剪
		intent.putExtra("crop", "true");
		// aspectX aspectY 是宽高的比例
		intent.putExtra("aspectX", BaseConfig.IMAGE_WIDTH);
		intent.putExtra("aspectY", BaseConfig.IMAGE_WIDTH);
		// outputX outputY 是裁剪图片宽高
		intent.putExtra("outputX", BaseConfig.IMAGE_WIDTH);
		intent.putExtra("outputY", BaseConfig.IMAGE_WIDTH);
		intent.putExtra("return-data", false);
		startActivityForResult(intent, requestCode);
	}

	private Uri getTempUri() {
		return Uri.fromFile(getTempFile());
	}

	private File getTempFile() {
		String savedir = XtomFileUtil.getTempFileDir(mContext);
		File dir = new File(savedir);
		if (!dir.exists())
			dir.mkdirs();
		// 保存入sdCard
		tempPath = savedir + XtomBaseUtil.getFileName() + ".jpg";// 保存路径
		File file = new File(tempPath);
		try {
			file.createNewFile();
		} catch (IOException e) {
			// TODO Auto-generated catch block
		}
		return file;
	}

	private void camera() {
		if (imagePathCamera == null) {
			imagePathCamera = imageWay.getCameraImage();
		}
		log_i("imagePathCamera=" + imagePathCamera);
		editImage(imagePathCamera, 3);
	}
}
